package com.foreverwin.mes.production.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.common.enums.IDUtils;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.meapi.model.Resrce;
import com.foreverwin.mes.production.model.CleanData;
import com.foreverwin.mes.production.model.ClockLog;
import com.foreverwin.mes.production.model.Station;
import com.foreverwin.mes.production.service.CleanDataService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.foreverwin.mes.production.service.CleanDataItemService;
import com.foreverwin.mes.production.model.CleanDataItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Max
 * @since 2020-02-11
 */
@Controller
@RequestMapping("/cleanDataItems")
public class CleanDataItemController {
    private final Logger logger = LoggerFactory.getLogger(CleanDataItemController.class);

    @Autowired
    public CleanDataItemService cleanDataItemService;
    @Autowired
    public CleanDataService cleanDataService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getCleanDataItemById(@PathVariable String id) {
        CleanDataItem result;
        try {
            result = cleanDataItemService.selectById(id);
        } catch (Exception e) {
            logger.error("getCleanDataItemById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    @ResponseBody
    @GetMapping("")
    public AjaxResult getCleanDataItemInfo(CleanData cleanData) {

        String workCenter = cleanData.getWokeCenter();
        String cleanName = cleanData.getCleanName();
        String site = CommonMethods.getSite();
        List<CleanDataItem> result;
        try {

            //查询清洁信息
            CleanData cleanDataInfo = cleanDataService.getCleanData(site, workCenter,cleanName);
            if (cleanDataInfo == null) {
                throw BusinessException.build("区域："+ workCenter + "的清洁名称"+ cleanName + "不存在");
            }
            String zCleanDataBo = cleanDataInfo.getHandle();

            //查询清洁信息明细
            List<CleanDataItem> cleanDataItems = cleanDataItemService.getCleanDataItemByZCDBo(zCleanDataBo);

            for (CleanDataItem cdl:cleanDataItems) {
                System.out.println( "测试"+cdl.toString());
            }
            if (cleanDataItems == null || cleanDataItems.size() < 1) {
                throw BusinessException.build("当前区域清洁信息明细未维护！");
            }
             result = cleanDataItems;

        } catch (Exception e) {
            return AjaxResult.error(StringUtils.isBlank(e.getMessage()) ? e.toString() : e.getMessage());
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getCleanDataItems")
    public AjaxResult getCleanDataItemList(CleanData cleanData){


        CleanDataItem cleanDataItem = new CleanDataItem();
        List<CleanDataItem> result;
        try {
            EntityWrapper<CleanDataItem> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(cleanDataItem);
            result = cleanDataItemService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getCleanDataItemList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getCleanDataItemPageList")
    public AjaxResult getCleanDataItemPageList(FrontPage<CleanDataItem> frontPage, CleanDataItem cleanDataItem){
        Page result;
        try {
            String site = CommonMethods.getSite();
            //cleanDataItem.setSite(site);
            EntityWrapper<CleanDataItem> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(cleanDataItem);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("zCleanDataBo", frontPage.getGlobalQuery())
                    .or().like("unitType", frontPage.getGlobalQuery())
                    .or().like("spotInspItem", frontPage.getGlobalQuery())
                    .or().like("workList", frontPage.getGlobalQuery())
                    .or().like("spotInspStandard", frontPage.getGlobalQuery())
                    .or().like("spotInspMethod", frontPage.getGlobalQuery())
                    .or().like("cleanTool", frontPage.getGlobalQuery())
                    .or().like("creator", frontPage.getGlobalQuery())
                    .or().like("updater", frontPage.getGlobalQuery())
        ;
            }
            result = cleanDataItemService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getCleanDataItemPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param cleanDataItem  传递的json
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult cleanDataItemSave(@RequestBody JSONObject cleanDataItem) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        String dataItemBo = "";
        String wokeCenter = cleanDataItem.getString("wokeCenter");
        String areaDesc = cleanDataItem.getString("areaDesc");
        String cleanName = cleanDataItem.getString("cleanName");
        int count = 0;
        try {
        CleanData cleanDataInfo = cleanDataService.getCleanData(site, wokeCenter,cleanName);
        if (cleanDataInfo != null) {
            dataItemBo = cleanDataInfo.getHandle();
        } else {//产生新的handle
            CleanData cleanData = new CleanData();
            cleanData.setHandle(IDUtils.createID());
            cleanData.setSite(site);
            cleanData.setWokeCenter(wokeCenter);
            cleanData.setCleanName(cleanName);
            cleanData.setAreaDesc( areaDesc );
            cleanData.setCreator( user );
            cleanData.setUpdater( user );
            cleanData.setCreatedDateTime(new Date());
            cleanData.setModifiedDateTime(new Date());
            cleanDataService.insert(cleanData);
            dataItemBo = cleanDataService.getCleanData(site, wokeCenter,cleanName).getHandle();
        }
        JSONArray dataItemJsonArray = cleanDataItem.getJSONArray("cleanParametersList");
        //int count = 0;
        if(dataItemJsonArray.size()>0){
            EntityWrapper<CleanDataItem> ew = new EntityWrapper<>();
            CleanDataItem cleanDataItem1 = new CleanDataItem();
            cleanDataItem1.setzCleanDataBo(dataItemBo);
            ew.setEntity(cleanDataItem1);
            cleanDataItemService.delete(ew);

            for(int i=0;i<dataItemJsonArray.size();i++){
                JSONObject job = dataItemJsonArray.getJSONObject(i);
                CleanDataItem cdi = job.toJavaObject(CleanDataItem.class);
                cdi.setzCleanDataBo(dataItemBo);
                cdi.setHandle(IDUtils.createID());
                cdi.setCreator( user );
                cdi.setUpdater( user );
                cdi.setCreatedDateTime(new Date());
                cdi.setModifiedDateTime(new Date());
                cleanDataItemService.insertOrUpdate(cdi);
                count=1;
            }
        }
        //try {
            //count = cleanDataItemService.insertOrUpdate(cleanDataItem) ? 1 : 0;
        } catch (Exception e) {
            logger.error("cleanDataItemSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : cleanDataItem);
    }

    /**
     * 删除
     * @param cleanDataItem  传递的Json
     * @return  null 失败
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_delete")
    public AjaxResult cleanDataItemDelete(@RequestBody JSONObject cleanDataItem) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        String dataItemBo = "";
        String wokeCenter = cleanDataItem.getString("wokeCenter");
        String cleanName = cleanDataItem.getString("cleanName");
        CleanData cleanDataInfo = cleanDataService.getCleanData(site, wokeCenter,cleanName);
        int count=1;
        if (cleanDataInfo != null) {
            dataItemBo = cleanDataInfo.getHandle();
            //删除主表信息
            EntityWrapper<CleanData> EntityWrapper = new EntityWrapper<>();
            CleanData cleanData = new CleanData();
            cleanData.setSite(site);
            cleanData.setWokeCenter(wokeCenter);
            cleanData.setCleanName(cleanName);
            EntityWrapper.setEntity(cleanData);
            cleanDataService.delete(EntityWrapper);
            //删除明细表信息
            EntityWrapper<CleanDataItem> ew = new EntityWrapper<CleanDataItem>();
            CleanDataItem cleanDataItem1 = new CleanDataItem();
            cleanDataItem1.setzCleanDataBo(dataItemBo);
            ew.setEntity(cleanDataItem1);
            cleanDataItemService.delete(ew);
        } else {//无需删除
            throw BusinessException.build("当前需要删除的区域清洁信息不存在！");
        }
        JSONArray dataItemJsonArray = cleanDataItem.getJSONArray("cleanParametersList");
        try {
            //count = cleanDataItemService.insertOrUpdate(cleanDataItem) ? 1 : 0;
        } catch (Exception e) {
            logger.error("cleanDataItemSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : cleanDataItem);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult cleanDataItemDelete(@PathVariable("id") String id){
        int count;
        try {
            count = cleanDataItemService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("cleanDataItemDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = cleanDataItemService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("cleanDataItemBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }
}